package com.aaron.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @Description
 * @Author Aaron
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2021/10/30
 */
public class XmlParseConfig {
    private Configuration configuration;

    public XmlParseConfig() {
        this.configuration = new Configuration();
    }

    public Configuration getConfiguration(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(inputStream);
        Element rootElement = doc.getRootElement();
        List<Element> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        list.forEach(e -> {
            properties.setProperty(e.attributeValue("name"), e.attributeValue("value"));
        });

        ComboPooledDataSource comboPooledDataSource = new
                ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        //填充 configuration
        configuration.setDataSource(comboPooledDataSource);
        Element mapperlocation = rootElement.element("mapperlocation");
        String mapperResource = mapperlocation.attributeValue("resource");
        XmlParseMapper xmlParseMapper = new XmlParseMapper(configuration);
        xmlParseMapper.parseMapper(mapperResource);
        return configuration;
    }
}
